package com.samshow.app;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.catalog.model.CatalogService;
import com.ecwid.consul.v1.health.model.Check;
import com.samshow.baseException.BaseException;
import com.samshow.baseVo.CaptionRequest;
import com.samshow.baseVo.DeleteCaptionRequest;
import com.samshow.config.WebSecurityConfigurer;
import com.samshow.service.BxClient;
import com.samshow.service.SampleService;
import com.samshow.service.SampleServiceClient;
import onbon.bx05.file.ControllerConfigBxFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2017/1/11.
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients("com.samshow.service")
@RestController
@ComponentScan("com.samshow.*")
@EnableRedisHttpSession
@Import(WebSecurityConfigurer.class)
public class ConsulApplication implements SampleService {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private SampleServiceClient sampleServiceClient;
    @Autowired
    private BxClient bxClient;
    @Autowired
    private MessageSource messageSource;
    @Autowired
    private ConsulClient consulClient;
    @RequestMapping("/")
    public String serviceUrl() {
        List<ServiceInstance> list = discoveryClient.getInstances("tsetConsulApp");
        if (list != null && list.size() > 0 ) {
            return list.get(0).getUri().toString();
        }
        return null;
    }


    @RequestMapping(value = "/setScreen",method = RequestMethod.GET)
    @ResponseBody
    public boolean setScreen() throws BaseException {
        ControllerConfigBxFile bxFile = new ControllerConfigBxFile();
        bxFile.setControllerName("TEST1");
        String netId = "aa";
        return bxClient.setScreen(netId,bxFile);
    }

    @RequestMapping(value = "/sendCaption",method = RequestMethod.GET)
    @ResponseBody
    public boolean sendCaption(@RequestBody CaptionRequest captionRequest) throws BaseException {
        return bxClient.sendCaption(captionRequest);
    }

    @RequestMapping(value = "/deleteProgran", method = RequestMethod.POST)
    @ResponseBody
    public boolean deletProgram(@RequestBody List<DeleteCaptionRequest> deleteCaptionRequest){
        return bxClient.deletProgram(deleteCaptionRequest);
    }

    @Value("${imessage.enable}")
    private String value;

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,String> test() {

        Map<String,String> map = new HashMap<String ,String>();
        map.put("test",value);
        return map;
    }


    @RequestMapping(value = "/unregister",method = RequestMethod.GET)
    @ResponseBody
    public String unregister() throws BaseException {
        Map<String, List<String>> map1 =  consulClient.getCatalogServices(null).getValue();
        for(String serviceName : map1.keySet()){
//            if("Consul-service".equals(serviceName))
//                continue;
            List<CatalogService> list = consulClient.getCatalogService(serviceName,null).getValue();

            for (CatalogService catalogService:list){
                List<Check> checks = consulClient.getHealthChecksForService(catalogService.getServiceName(),null).getValue();
                for (Check check:checks){
                    if (!check.getStatus().name().equals(Check.CheckStatus.PASSING.name())){
                        consulClient.agentCheckDeregister(check.getCheckId());
                        //consulClient.agentServiceDeregister(check.getServiceId());
                    }
                }
                // consulClient.agentServiceDeregister(catalogService.getServiceId());
            }

//            List<HealthService> response = consulClient.getHealthServices(serviceName,false,null).getValue();
//            for(HealthService service : response) {
//                ConsulClient clearClient = new ConsulClient(service.getNode().getAddress(), 8500);
//                service.getChecks().forEach(check -> {
//                        System.out.println("unregister : {}"+ check.getServiceId());
//                        clearClient.agentServiceDeregister(check.getServiceId());
//                });
//            }
        }
        return  null;
    }

    public static void main(String[] args) {
        SpringApplication.run(ConsulApplication.class, args);
    }

    @Override
    public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
        return sampleServiceClient.add(a,b);
    }
}
